package com.base.lib.widget;

import android.content.Context;
import android.net.http.SslError;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.base.lib.R;
import com.base.lib.util.ScreenUtils;

public class CustomWebView extends WebView {

    private ProgressBar progressbar;

    public CustomWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    public CustomWebView(Context context) {
        this(context, null);
    }

    public CustomWebView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);

    }

    private void init(Context context) {
        progressbar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
        progressbar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, (int) ScreenUtils.dpToPx(context, 2), 0, 0));
        progressbar.setProgressDrawable(getResources().getDrawable(R.drawable.progress_bar));
        addView(progressbar);

        WebSettings webSettings = getSettings();
        webSettings.setJavaScriptEnabled(true);

        // 自适应屏幕
        webSettings.setUseWideViewPort(true);
        webSettings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL);
        webSettings.setLoadWithOverviewMode(true);

        // 设置可以支持缩放
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(false);

        // 设置编码
        webSettings.setDefaultTextEncodingName("gb2312");
        // 设置默认缩放级别
        webSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
        // 设置可以访问文件
        webSettings.setAllowFileAccess(true);
        // 设置UA
        webSettings.setUserAgentString(webSettings.getUserAgentString() + "&#160;fht-Android");
        // 设置字体大小
        webSettings.setTextSize(WebSettings.TextSize.NORMAL);
        // 以单列的形式排列布局
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        // 设置缓存模式:解决7.0缓存问题
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        // 设置自适应屏幕大小
        webSettings.setUseWideViewPort(true);
        // 缩放至屏幕的大小
        webSettings.setLoadWithOverviewMode(true);
        // HTML5 的 DOM Storage 机制提供了一种方式让程序员能够把信息存储到本地的计算机上，在需要时获取
        webSettings.setDomStorageEnabled(true);

        // android 5.0以上默认不支持Mixed Content
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(
                    WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
        }

        setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        setWebViewClient(new CommonWebViewClient());
        setWebChromeClient(new CommonWebChromeClient());
    }

    private boolean hasAd(String url) {
        String[] adBlockUrl = {
                "ubmcmm.baidustatic.com",
                "cpro2.baidustatic.com",
                "cpro.baidustatic.com",
                "s.lianmeng.360.cn",
                "nsclick.baidu.com",
                "pos.baidu.com",
                "bjs.baidu.com",
                "cpro.baidu.com",
                "images.sohu.com/cs/jsfile/js/c.js",
                "union.sogou.com/",
                "sogou.com/",
                "a.baidu.com",
                "c.baidu.com",

        };
        for (String adUrl : adBlockUrl) {
            if (url.contains(adUrl)) {
                return true;
            }
        }
        return false;
    }

    class CommonWebViewClient extends WebViewClient {
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            super.onReceivedSslError(view, handler, error);
            // handler.cancel();// Android默认的处理方式
            handler.proceed();// 接受所有网站的证书
            // handleMessage(Message msg);// 进行其他处理
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            url = url.toLowerCase();
            if (!hasAd(url)) {
                //正常加载
                return super.shouldInterceptRequest(view, url);
            } else {
                //含有广告资源屏蔽请求
                return new WebResourceResponse(null, null, null);
            }
        }
    }

    class CommonWebChromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                progressbar.setVisibility(GONE);
            } else {
                if (progressbar.getVisibility() == GONE) {
                    progressbar.setVisibility(VISIBLE);
                }
                progressbar.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }
    }

}
